import React from 'react';
import { Editor } from '@tiptap/react';

interface TextFormatButtonProps {
  editor: Editor;
  type: string;
  icon: string;
  title?: string;
  level?: number;
}

const TextFormatButton: React.FC<TextFormatButtonProps> = ({
  editor,
  type,
  icon,
  title,
  level
}) => {
  const isActive = level 
    ? editor.isActive('heading', { level }) 
    : editor.isActive(type);

    const onClick = () => {
      if (type === 'heading' && level) {
        editor.chain().focus().toggleHeading({ level }).run();
      } else {
        // 使用类型安全的方式处理命令
        const command = `toggle${type.charAt(0).toUpperCase()}${type.slice(1)}`;
        if (command in editor.chain().focus()) {
          (editor.chain().focus() as any)[command]().run();
        } else {
          console.warn(`不支持的格式化命令: ${command}`);
        }
      }
    };

  return (
    <button
      onClick={onClick}
      className={`toolbar-button ${isActive ? 'is-active' : ''}`}
      title={title}
    >
      <i className="icon">{icon}</i>
    </button>
  );
};

export default TextFormatButton;